<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" fullscreen>
    <el-form ref="formRef" :model="formData" size="large" :rules="formRules" label-width="100px"
      v-loading="formLoading">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="等级" prop="levelName">
            <el-input disabled v-model="formData.levelName" placeholder="请输入等级" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="说明" prop="levelName">
            <el-input disabled v-model="formData.description" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属范围" prop="belongType">
            <el-select v-model="formData.belongType" placeholder="请选择所属范围">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.BELONG)" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年月" prop="planDate">
            <el-date-picker v-model="formData.planDate" type="month" value-format="YYYY-MM-DD" placeholder="选择年月" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="排除日期" prop="excludeDate">
            <el-date-picker v-model="formData.excludeDate" type="date" value-format="x" placeholder="选择排除日期" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="近期关注问题" prop="careProblem">
            <el-input type="textarea" v-model="formData.careProblem" placeholder="请输入近期关注问题" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <el-table border :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }" :data="areaList" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" align="center" />
      <el-table-column label="区域" align="center" prop="areaName" width="350" />
      <el-table-column label="审核日期" width="350" align="center">
        <template #default="scope">
          <el-date-picker v-model="scope.row.auditStartDate" type="date" value-format="YYYY-MM-DD"
            placeholder="选择审核日期" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="审核结束日期" width="250" align="center">
            <template #default="scope">
              <el-date-picker v-model="scope.row.auditEndDate" type="date" value-format="x" placeholder="选择审核结束日期" />
            </template>
          </el-table-column> -->
      <el-table-column label="审核人" min-width="150" align="center">
        <template #default="scope">
          <el-select clearable multiple filterable v-model="scope.row.auditUserId" placeholder="请选择审核人,支持模糊搜索">
            <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
          </el-select>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { AuditPlanApi, AuditPlan } from '@/api/business/auditplan'
import AuditPlanAreaForm from './components/AuditPlanAreaForm.vue'
import * as UserApi from '@/api/system/user'

/** 审核计划 表单 */
defineOptions({ name: 'AuditPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  levelId: undefined,
  belongType: undefined,
  planDate: undefined,
  excludeDate: undefined,
  careProblem: undefined,
  remark: undefined,
  snedUserId: undefined,
  status: undefined,
  season: undefined,
  levelName: undefined,
  description: '',
  auditPlanAreas: []

})
const formRules = reactive({
  snedUserId: [{ required: true, message: '下发人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('auditPlanArea')

/** 打开弹窗 */
const open = async (level, id?: number, type) => {
  formType.value = type

  await getAreaList(id)

  dialogVisible.value = true
  resetForm()

  //
  formData.value.levelId = level.id
  formData.value.levelName = level.levelName
  formData.value.description = level.description
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AuditPlanApi.getAuditPlan(id)
    } finally {
      formLoading.value = false
    }
  }


}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

//获取所有区域
const areaList = ref([])

const getAreaList = async (id) => {
  if (id) {
    areaList.value = await AuditPlanApi.getAuditPlanAreaListByPlanId(id)
  } else {
    areaList.value = await AuditPlanApi.getAreaList()
  }

}


//用户列表
const userList = ref([])

const initUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AuditPlan
    // 拼接子表的数据

    const valid = validateAuditPlanAreas(areaList.value);

    if (!valid) {
      return; // 校验失败，阻止后续操作
    }

    data.auditPlanAreas = areaList.value
    if (formType.value === 'add') {
      await AuditPlanApi.createAuditPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await AuditPlanApi.updateAuditPlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 校验函数
function validateAuditPlanAreas(areaList) {
  for (let i = 0; i < areaList.length; i++) {
    const item = areaList[i];

    // 校验审核日期
    if (!item.auditStartDate || item.auditStartDate.trim() === '') {
      ElMessage.error(`第 ${i + 1} 行：请选择审核日期`);
      return false;
    }

    // 校验审核人（multiple，所以是数组）
    if (!item.auditUserId || !Array.isArray(item.auditUserId) || item.auditUserId.length === 0) {
      ElMessage.error(`第 ${i + 1} 行：请至少选择一名审核人`);
      return false;
    }

    // 可选：校验日期格式是否合法（防止手动输入或异常值）
    const date = new Date(item.auditStartDate);
    if (isNaN(date.getTime())) {
      ElMessage.error(`第 ${i + 1} 行：审核日期格式无效`);
      return false;
    }
  }

  return true; // 全部通过
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    levelId: undefined,
    belongType: undefined,
    planDate: undefined,
    excludeDate: undefined,
    careProblem: undefined,
    remark: undefined,
    snedUserId: undefined,
    status: undefined,
    season: undefined,
    levelName: undefined,
    description: '',
    auditPlanAreas: []
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(async () => {
  initUserList()
})

</script>
